package cn.zmit.kuxi.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.binner.SliderBanner;
import cn.zmit.kuxi.adapter.MainSliderBannerOne;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.image.ImageDisplayer;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class WillAnnounceActivity extends BaseActivity {

	@ViewInject(R.id.tv_current_goods_image_item)
	private TextView tv_current_goods_image_item;
	@ViewInject(R.id.tv_all_goods_image_count)
	private TextView tv_all_goods_image_count;
	@ViewInject(R.id.tv_announce_title_join)
	private TextView tv_announce_title_join;
	@ViewInject(R.id.tv_announce_detail_data)
	private TextView tv_announce_detail_data;
	@ViewInject(R.id.tv_announce_introduction)
	private TextView tv_announce_introduction;
	@ViewInject(R.id.progressBarPeople)
	private ProgressBar progressBarPeople;
	@ViewInject(R.id.tv_announce_allPeople)
	private TextView tv_announce_allPeople;
	@ViewInject(R.id.tv_announce_alreadyJoin)
	private TextView tv_announce_alreadyJoin;
	@ViewInject(R.id.tv_announceCountdown)
	private TextView tv_announceCountdown;
	@ViewInject(R.id.tv_time)
	private TextView tv_time;

	@ViewInject(R.id.tv_userPhone)
	private TextView tv_userPhone;
	@ViewInject(R.id.tv_luckyNum)
	private TextView tv_luckyNum;
	@ViewInject(R.id.rl_join_record)
	private RelativeLayout rl_join_record;
	@ViewInject(R.id.rl_old_record)
	private RelativeLayout rl_old_record;
	@ViewInject(R.id.rl_old_share)
	private RelativeLayout rl_old_share;
	@ViewInject(R.id.btn_JoinNext)
	private Button btn_JoinNext;
	private String gp_id, title, goodsName, goodsId;
	private Map<String, String> map;
	private List<String> kList;
	private List<String> vlist;
	String[] karray;
	String[] varray;
	String announceOn, butCount, joinTime;// 揭晓时间
	@ViewInject(R.id.rl_user)
	private LinearLayout rl_user;

	@ViewInject(R.id.rl_root_time)
	private RelativeLayout rl_daojishi;// 倒计时
	@ViewInject(R.id.ll_root)
	private LinearLayout ll_jiexiao;// 已揭晓用户信息
	@ViewInject(R.id.imag_win_pic)
	private ImageView imag_win_pic;//

	@ViewInject(R.id.tv_win_title)
	private TextView tv_win_title;//

	@ViewInject(R.id.tv__win_join_num)
	private TextView tv__win_join_num;//

	@ViewInject(R.id.tv_win_num)
	private TextView tv_win_num;//

	@ViewInject(R.id.tv_win_time)
	private TextView tv_win_time;//
	String pic;// 中奖用户头像地址

	@ViewInject(R.id.slider_banner)
	private SliderBanner sliderBanner;
	/**
	 * 轮播图控制器
	 */
	private MainSliderBannerOne mainSliderBanner;

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	int flagtime = 0;
	/**
	 * 装ImageView数组
	 */
	private ImageView[] mImageViews;
	private List<String> strings;
	int hour = -1;
	int minute = -1;
	int second = -1;
	final static String tag = "tag";
	int c;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case 0:
				if (hour == 0) {
					if (minute == 0) {
						if (second == 0) {// 时间到

							Date();

							if (timer != null) {
								timer.cancel();
								timer = null;
							}
							if (timerTask != null) {
								timerTask = null;
							}
						} else {// 00:30,00:08
							second--;
							if (second >= 10) {
								tv_time.setText("0" + hour + ":" + "0" + minute
										+ ":" + second);
							} else {
								tv_time.setText("0" + hour + ":" + "0" + minute
										+ ":0" + second);
							}
						}
					} else {// minute!=0,33:00->32:59
						if (second == 0) {
							second = 59;
							minute--;
							if (minute >= 10) {// 33:30
								tv_time.setText("0" + hour + ":" + minute + ":"
										+ second);
							} else {// 06:30
								tv_time.setText("0" + hour + ":" + "0" + minute
										+ ":" + second);
							}
						} else {// 32:30->32:29
							second--;
							if (second >= 10) {
								if (minute >= 10) {
									tv_time.setText("0" + hour + ":" + minute
											+ ":" + second);
								} else {// 09:30
									tv_time.setText("0" + hour + ":" + "0"
											+ minute + ":" + second);
								}
							} else {// 12:30
								if (minute >= 10) {
									tv_time.setText("0" + hour + ":" + minute
											+ ":0" + second);
								} else {// 08:30
									tv_time.setText("0" + hour + ":" + "0"
											+ minute + ":0" + second);
								}
							}
						}
					}
				}
				// hour>0
				else {
					if (minute == 0) {// hour>0,minute=0
						if (second == 0) {
							minute = 59;
							second = 59;
							hour--;
							if (hour >= 10) {
								if (second >= 10) {
									tv_time.setText(hour + ":" + minute + ":"
											+ second);
								} else {
									tv_time.setText(hour + ":" + minute + ":0"
											+ second);
								}
							} else {
								if (second >= 10) {
									tv_time.setText("0" + hour + ":" + minute
											+ ":" + second);
								} else {
									tv_time.setText("0" + hour + ":" + minute
											+ ":0" + second);
								}
							}
						} else {
							second--;
							if (hour >= 10) {
								if (second >= 10) {
									tv_time.setText(hour + ":0" + minute + ":"
											+ second);
								} else {
									tv_time.setText(hour + ":0" + minute + ":0"
											+ second);
								}
							} else {
								if (second >= 10) {
									tv_time.setText("0" + hour + ":0" + minute
											+ ":" + second);
								} else {
									tv_time.setText("0" + hour + ":0" + minute
											+ ":0" + second);
								}
							}
						}
					} else {// hour>0,minute!=0
						if (second == 0) {
							second = 59;
							minute--;
							if (hour >= 10) {
								if (second >= 10) {
									if (minute >= 10) {
										tv_time.setText(hour + ":" + minute
												+ ":" + second);
									} else {
										tv_time.setText(hour + ":0" + minute
												+ ":" + second);
									}
								} else {
									if (minute >= 10) {
										tv_time.setText(hour + ":" + minute
												+ ":0" + second);
									} else {
										tv_time.setText(hour + ":0" + minute
												+ ":0" + second);
									}
								}
							} else {
								if (second >= 10) {
									if (minute >= 10) {
										tv_time.setText("0" + hour + ":"
												+ minute + ":" + second);
									} else {
										tv_time.setText("0" + hour + ":0"
												+ minute + ":" + second);
									}
								} else {
									if (minute >= 10) {
										tv_time.setText("0" + hour + ":"
												+ minute + ":0" + second);
									} else {
										tv_time.setText("0" + hour + ":0"
												+ minute + ":0" + second);
									}
								}
							}

						} else {
							second--;
							if (hour >= 10) {
								if (second >= 10) {
									if (minute >= 10) {
										tv_time.setText(hour + ":" + minute
												+ ":" + second);
									} else {
										tv_time.setText(hour + ":0" + minute
												+ ":" + second);
									}
								} else {
									if (minute >= 10) {
										tv_time.setText(hour + ":" + minute
												+ ":0" + second);
									} else {
										tv_time.setText(hour + ":0" + minute
												+ ":0" + second);
									}
								}
							} else {
								if (second >= 10) {
									if (minute >= 10) {
										tv_time.setText("0" + hour + ":"
												+ minute + ":" + second);
									} else {
										tv_time.setText("0" + hour + ":0"
												+ minute + ":" + second);
									}
								} else {
									if (minute >= 10) {
										tv_time.setText("0" + hour + ":"
												+ minute + ":0" + second);
									} else {
										tv_time.setText("0" + hour + ":0"
												+ minute + ":0" + second);
									}
								}
							}

						}
					}
				}

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		};
	};
	private String flag = null;
	@SuppressLint("HandlerLeak")
	private Handler userHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 2000:
				if (msg.obj != null) {
					tv_userPhone.setText(msg.obj + "");
				} else {
					tv_userPhone.setText("");
				}

				break;

			default:
				break;
			}
			super.handleMessage(msg);
		};
	};
	@SuppressLint("HandlerLeak")
	private Handler luckHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 3000:
				if (msg.obj != null) {
					tv_luckyNum.setText(msg.obj + "");
				} else {
					tv_luckyNum.setText("");
				}

				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setTitleView("最新喜报", true);
		setContentView(R.layout.activity_will_announce);
		ViewUtils.inject(this);
		LinearLayout ll_root = (LinearLayout) findViewById(R.id.ll_root);

		final Boolean has_login = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		ll_root.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (has_login) {
					Intent intent = new Intent(WillAnnounceActivity.this,
							HisCenterActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("win_id", winnerId);
					intent.putExtras(bundle);
					startActivity(intent);
				} else {
					Toast.makeText(context, "登陆后可查看！", 0).show();
				}

			}
		});

		// next_gp_id = getIntent().getStringExtra("next_gp_id");

		flag = getTextFromBundle("flag");
		if (flag != null && flag.equals("首页")) {
			gp_id = getTextFromBundle("gp_id");
			title = getTextFromBundle("title");
			goodsName = getTextFromBundle("goodsName");
			// getData();
			initPtr();
		} else {
			gp_id = getTextFromBundle("gp_id");
			title = getTextFromBundle("title");
			goodsName = getTextFromBundle("goodsName");
			initPtr();
		}
		initSliderBanner();
	}

	/**
	 * 初始化轮播图
	 */
	private void initSliderBanner() {
		RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(
				ScreenUtils.getScreenWidth(context),
				(int) (ScreenUtils.getScreenWidth(context) * 1f / 16 * 9.6f));
		sliderBanner.setLayoutParams(lyp);
		mainSliderBanner = new MainSliderBannerOne(sliderBanner);
	}

	private void getData() {
		RequestTask.getInstance().getAnnounced(this, gp_id,
				new onRequestListener());
	}

	private String nowTime;
	long time;
	String lucky_phone;
	String lucky_number;
	long timedate;
	String winnerId;
	private String next_gp_id;

	private class onRequestListener extends OnRequestListenerAdapter<Object> {

		@SuppressLint("SimpleDateFormat")
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			JsonData data = jsonData.optJson("announce_info");

			if (data != null && data.length() > 0) {
				gp_id = data.optString("gp_id");
				lucky_number = data.optString("lucky_number");
				lucky_phone = data.optString("lucky_phone");
				announceOn = data.optString("announceOn");
				butCount = data.optString("buy_count");
				joinTime = data.optString("buy_on");
				pic = data.optString("avatar");
				nowTime = data.optString("now_time");
				goodsId = data.optString("goods_id");
				winnerId = data.optString("winner_id");
				next_gp_id = data.optString("next_gp_id");
				String description = data.optString("description");
				String pictures = data.optString("pictures");
				String price = data.optString("price");
				mainSliderBanner.play(data.optJson("banner"), true);

				tv_announce_title_join.setText("第" + title + "期");
				tv_announce_detail_data.setText(goodsName);
				tv_announce_introduction.setText(description);
				tv_announce_allPeople.setText("总需人数：" + price);
				tv_announce_alreadyJoin.setText("已参与：" + price);

				double all = Integer.parseInt(price);
				double join = Integer.parseInt(price);
				final double result = ((join / all) * 100);
				progressBarPeople.setMax(100);
				progressBarPeople.setProgress((int) result);

				Log.e("gp_id====", gp_id);
				Log.e("next_gp_id====", next_gp_id);

			}
			JsonData number = jsonData.optJson("sole_numbers");
			map = new HashMap<String, String>();

			if (number != null && number.length() > 0) {
				for (int i = 0; i < number.length(); i++) {
					JsonData itemDate = number.optJson(i);
					String phone = itemDate.optString("phone");
					String num = itemDate.optString("sole_number");

					map.put(num, phone);
				}

				for (Map.Entry<String, String> entry : map.entrySet()) {
					System.out.println("+++++++++key+++++++++++"
							+ entry.getKey() + "____________values__________"
							+ entry.getValue());

				}
				kList = new ArrayList<String>();
				for (String key : map.keySet()) {// 幸运码
					kList.add(key);
				}
				System.out.println(kList);
				int size = kList.size();
				karray = (String[]) kList.toArray(new String[size]);// 转数组形式
				String Num = "";
				for (int i = 0; i < karray.length; i++) {
					Num += karray[i];
				}
				// System.out.println("hhhhhhhhhhhhhhhhhhh" + Num + "77SSSSSS"
				// + karray[3]);
				vlist = new ArrayList<String>();
				for (String values : map.values()) {// 手机号
					vlist.add(values);
				}
				int vsize = vlist.size();
				varray = (String[]) vlist.toArray(new String[vsize]);// 转数组形式

				String phone = "";
				for (int i = 0; i < varray.length; i++) {
					phone += varray[i];
				}
				// System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPP" + phone);
				// 倒计时时间处理

				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				try {
					Date old = sdf.parse(announceOn);
					Date newTime = sdf.parse(nowTime);
					String xx = getBeapartDate(getSecond(newTime, old));

					System.out.println("第一位数" + xx.substring(0, 1) + "第二位数"
							+ xx.substring(1, xx.length()));
					int m = Integer.parseInt(xx.substring(0, 1));
					int s = Integer.parseInt(xx.substring(1, xx.length()));
					System.out.println("mmmmmmmmmmm" + m + "ssssssssssssssss"
							+ s);

					if (m > 5) {// 已揭晓
						Date();
					} else {// 倒计时
						ll_jiexiao.setVisibility(View.GONE);
						rl_daojishi.setVisibility(View.VISIBLE);
						rl_user.setVisibility(View.VISIBLE);
						if (map != null && map.size() > 0) {
							if (hour == -1 && minute == -1 && second == -1) {
								hour = 0;
								minute = m;
								second = s;
							}
							tv_time.setText(hour + ":" + minute + ":" + second);
							if (flagtime == 0) {
								flagtime = 1;
								start();

							}
							// 启动倒计时
							// StartUserName();// 启动用户名变化
							// StartLuckName();// 启动幸运码变化
						}
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ptr_view.refreshComplete();
			}

		}
	}

	/**
	 * 根据所给日期返回两日期相差的秒数
	 * 
	 * @param d1
	 * @param d2
	 * @return 返回两个日期间隔的毫秒数
	 */

	public static long getSecond(Date d1, Date d2) {
		long a1 = d1.getTime();
		long a2 = d2.getTime();
		long a3 = (a1 - a2) / 1000;
		System.out.println("aaaaaaaaaaaa" + a3);

		return a3;

	}

	/**
	 * 根据所秒数,计算相差的时间并以**时**分**秒返回
	 * 
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static String getBeapartDate(long m) {
		System.out.println("mmmmmmmmmm" + m);
		// String beapartdate = "";
		if (m <= 300) {
			int nDay = (int) m / (24 * 60 * 60);
			int nHour = (int) (m - nDay * 24 * 60 * 60) / (60 * 60);
			int nMinute = (int) (m - nDay * 24 * 60 * 60 - nHour * 60 * 60) / 60;
			int nSecond = (int) m - nDay * 24 * 60 * 60 - nHour * 60 * 60
					- nMinute * 60;
			// beapartdate = nDay + "天" + nHour + "小时" + nMinute + "分" + nSecond
			// + "秒";
			int resultOne = 5 * 60 - (nMinute * 60 + nSecond);// 计算两个日期差多少秒
			int fen = resultOne / 60;
			int miao = resultOne % 60;
			System.out.println("两个日期差：" + resultOne);
			System.out.println("计算前分" + nMinute + "秒" + nSecond);
			System.out.println("分" + fen + "秒" + miao);
			return fen + "" + miao + "";
		} else {
			return "66";
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	private void Date() {
		rl_daojishi.setVisibility(View.GONE);
		rl_user.setVisibility(View.GONE);
		ll_jiexiao.setVisibility(View.VISIBLE);

		tv_win_title.setText("获奖用户：" + lucky_phone);
		tv__win_join_num.setText("参加次数：" + butCount);

		tv_win_num.setText("幸运码：" + lucky_number);
		tv_win_time.setText("参与时间：" + joinTime);
		if (pic != null && pic.length() > 0) {
			ImageDisplayer.getInstance().dispalyImageWithRadius(
					Url.IMAGR_ROOT + pic, imag_win_pic, 0);
		} else {
			imag_win_pic.setImageResource(R.drawable.user_pic_def);
		}
	}

	// 计时器
	private Timer timer;
	private TimerTask timerTask;
	int k = 0;
	int v = 0;
	private Timer timerUser;// 用户名
	private TimerTask timerTaskUser;
	private Timer timerLuck;// 幸运码
	private TimerTask timerTaskLuck;

	// private void StartLuckName() {
	// timerTaskLuck = new TimerTask() {
	//
	// @Override
	// public void run() {
	// Message message = new Message();
	// message.what = 3000;
	// if (karray != null && karray.length > 0 && k < karray.length) {
	// message.obj = karray[k];
	// k++;
	// }
	// luckHandler.sendMessage(message);
	// }
	// };
	// timerLuck = new Timer();
	// timerLuck.schedule(timerTaskLuck, 0, 1000);
	// }
	//
	// private void StartUserName() {// 用户名
	//
	// timerTaskUser = new TimerTask() {
	//
	// @Override
	// public void run() {
	// Message message = new Message();
	// message.what = 2000;
	// if (varray != null && varray.length > 0 && v < varray.length) {
	// message.obj = varray[v];
	// v++;
	// }
	//
	// userHandler.sendMessage(message);
	// }
	// };
	// timerUser = new Timer();
	// timer.schedule(timerTaskUser, 0, 1000);
	// }

	private void start() {

		timerTask = new TimerTask() {
			@Override
			public void run() {

				Message msgThree = new Message();
				msgThree.what = 0;
				handler.sendMessage(msgThree);
			}
		};
		timer = new Timer();
		timer.schedule(timerTask, 0, 1000);

	}

	@OnClick({ R.id.btn_JoinNext, R.id.rl_old_share, R.id.rl_old_record,
			R.id.rl_join_record })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.btn_JoinNext:// 参与下一期
			Intent intent = new Intent();
			Bundle bundle_next = new Bundle();
			bundle_next.putString("gp_id", next_gp_id);
			intent.putExtras(bundle_next);
			intent.setClass(context, GoodsDetailActivity.class);
			context.startActivity(intent);
			break;
		case R.id.rl_old_share:// 往期晒单
			Bundle bundle2 = new Bundle();
			bundle2.putString("goods_id", goodsId);
			openActivity(OldShareActivity.class, bundle2);
			break;
		case R.id.rl_old_record:// 往期揭晓
			Bundle bundle1 = new Bundle();
			bundle1.putString("goods_id", goodsId);
			openActivity(OldAnnouncedActivity.class, bundle1);
			break;
		case R.id.rl_join_record:// 参与记录
			Bundle bundle = new Bundle();
			bundle.putString("gp_id", gp_id);
			openActivity(JoinUserActivity.class, bundle);
			break;

		default:
			break;
		}
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {

						getData();

					}

				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

}
